<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of clsLoginMgt
 *
 * @author Rose Epinglee™
 */
defined('SYSPATH') or die('No direct script access.');

Class Controller_Helper_Authentication {

    public static $_key = "user";

    public function __construct() {
        $config = Kohana::$config->load('config');
        $this->_key = $config->admin_session_key;
    }

    /**
     *
     * @param <type> $oUser
     * @param <type> $key 
     */
    public static function set_session($oUser, $key = null) {
        if ($key === null) {
            $config = Kohana::$config->load('config');
            $key = $config->admin_session_key;
        }
        $session = Session::instance();
        $session->set($key, $oUser);
    }

    //--------------------------------------------------
    public static function check_session($key = null) {
        if ($key === null) {
            $config = Kohana::$config->load('config');
            $key = $config->admin_session_key;
        }
        $session = Session::instance();
        $login = $session->get($key);
        if (empty($login)) {
            return false;
        }
        return true;
    }

    //--------------------------------------------------
    public static function clear_session($key = null) {
        if ($key === null) {
            $config = Kohana::$config->load('config');
            $key = $config->admin_session_key;
        }
        $session = Session::instance();
        $session->delete($key);
    }

    //--------------------------------------------------
    public static function get_session($key = null) {
        if ($key === null) {
            $config = Kohana::$config->load('config');
            $key = $config->admin_session_key;
        }
        $session = Session::instance();
        return $session->get($key);
    }

    //--------------------------------------------------
    public static function encode_password($password) {
        return self::hash($password);
    }

    /**
     * Perform a hmac hash, using the configured method.
     * Creates a hashed hmac password from a plaintext password. This
     * method is deprecated, [Auth::hash] should be used instead.
     * @param   string  string to hash
     * @return  string
     */
    public static function hash($str) {
        $config = Kohana::$config->load('config');
        if (!$config['hash_key'])
            hash_hmac('md5', $str, '4b 8?((~FKnpD))>8kb!B |#-uXIO24G3rc:&MG+FR{x;r#Uq4k{Ef@F4E9^-qS!');

        return hash_hmac($config['hash_method'], $str, $config['hash_key']);
    }

    /**
     * The letter l (lowercase L) and the number 1
     * have been removed, as they can be mistaken
     * for each other.
     */
    public static function generate_password() {
        $chars = "abcdefghijkmnopqrstuvwxyz023456789";
        srand((double) microtime() * 1000000);
        $i = 0;
        $pass = '';
        while ($i <= 7) {
            $num = rand() % 33;
            $tmp = substr($chars, $num, 1);
            $pass = $pass . $tmp;
            $i++;
        }
        return $pass;
    }

    public static function permission_admin($directory, $controller, $action) {
        $session_user = Controller_Helper_Authentication::get_session();
        $a_result = array('permission' => true, 'redirect' => URL::base() . 'admin/auth/login?logout=1');
        // check session

        if ($session_user instanceof Domain_Entities_User) {
            if ($session_user->getId() <= 0 || $session_user->getoutsideaccess() != 1) {
                $a_result['permission'] = false;
                return $a_result;
            }
            //else
            //upadte expired time
            $s_user = new Model_Service_User;
            $s_su = new Model_Service_Session_User();

            $o_user = $s_user->load($session_user->getId());
            $o_entity_user = $o_user->get_data();
            $o_su = $o_entity_user->get_Sessionuser();
            $o_entity_su = $o_su->get_data();
            // check expired time
            $todays_date = date("Y-m-d H:i:s", strtotime("now"));

            $today = strtotime($todays_date);
            $expired_time = $o_entity_su->getExpired();
            $expiration_date = strtotime($expired_time);

            if ($expiration_date <= $today) {
                $a_result['permission'] = false;
                return $a_result;
            }

            if ($o_entity_user->getId() <= 0) {
                $a_result['permission'] = false;
                return $a_result;
            }
            $o_config = Kohana::$config->load('config');
            $expired_time = $o_config->expired_time;
            $date = strtotime(date("Y-m-d H:i:s"));
            $expired = date("Y-m-d H:i:s", strtotime("+$expired_time minutes"));
            $o_entity_su->setExpired($expired);
            $s_su->update($o_entity_su);
            // Super User is admin
            if ($session_user->getadmin_supor() != 1) {
                //load cache
                $cache = Cache::instance();
                $a_permisstion = $cache->get(Controller_Helper_Constant::CACHE_ADMIN_PERMISSION);
                $a_permisstion_user = $cache->get(Controller_Helper_Constant::CACHE_ADMIN_PERMISSION_USER . $session_user->getId());
                
                // check acction and controller have permission
                $b_is_check_permission = false;
                
                if (!empty($a_permisstion)) {
                    $s_url_back = "";
                    // check acction and controller in table permission
                    foreach ($a_permisstion as $o_per) {
                        if ($o_per instanceof Domain_Entities_Permission && $controller === $o_per->get__Controller() && $action === $o_per->getName()) {
                            $b_is_check_permission = true;
                            $s_url_back = $o_per->getBack_url();
                            break;
                        }
                    }

                    $b_is_per = true;
                    // if permission_user empty and check permission, then action is not permission
                    if (empty($a_permisstion_user) && $b_is_check_permission) {
                        $b_is_per = false;
                    }
                    //if permission_user in not empty and check permission
                    if ($b_is_check_permission && $b_is_per && !empty($a_permisstion_user)) {
                        foreach ($a_permisstion_user as $o_entity_pu) {
                            if ($o_entity_pu instanceof Domain_Entities_Permission && $controller === $o_entity_pu->get__Controller() && $action === $o_entity_pu->getName()) {
                                $b_is_per = true;
                                break;
                            } else {
                                $b_is_per = false;
                            }
                        }
                    }

                    // action is not permission then return url back(controller/list) or url_back in db
                    if (!$b_is_per && !($controller == 'user' && $action == 'profile' && $o_entity_user->getId() == Arr::get($_REQUEST, 'userid'))) {
                        $a_result['permission'] = false;
                        if (!empty($s_url_back)) {
                            $a_result['redirect'] = URL::base() . $s_url_back;
                        } else {
                            $a_result['redirect'] = URL::base() . $directory . "/" . $controller . "/list";
                        }
                    } else {
                        $a_result['permission'] = true;
                        return $a_result;
                    }
                }
            } else {
                $a_result['permission'] = true;
                return $a_result;
            }
        }
        // back page login(lost session)
        else {
            $a_result['permission'] = false;
            return $a_result;
        }
        $a_result['redirect'] = URL::base() . "admin/home/index";
        return $a_result;
    }

    public static function check_permission_admin($directory, $controller, $action) {
        $a_result = self::permission_admin($directory, $controller, $action);
        return $a_result['permission'];
    }

}

?>
